import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从请求中获取用户名密码
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || password ==null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码为空!登录失败!");
            return;
        }
        //查询数据库 验证
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user == null || !user.getPassword().equals(password)) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误!登陆失败!");
            return;
        }
        //如果正确 创建一个会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);

        //构建302响应报文
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //判定当前登陆状态
        //获取当前会话
        HttpSession session = req.getSession(false);
        if(session == null) {
            resp.setStatus(403);
            return;
        }

        User user = (User)session.getAttribute("user");
        //有会话 没有user
        if(user == null) {
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);



    }
}
